package Utils;

import annotation.Controller;
import annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ControllerComponent {
    private static volatile ControllerComponent controllerComponent;
    private static Map<String,Object> controllerBean = new HashMap<>();
    public static ControllerComponent getControllerComponent(){
        if(controllerComponent == null){
            synchronized (ControllerComponent.class){
                controllerComponent = new ControllerComponent();
            }
        }
        return controllerComponent;
    }
    public static Object doFilter(String str){
        Object o;
        if((o = controllerBean.get(str)) != null){
            Class<?> klass = o.getClass();
            Method[] methods = klass.getMethods();
            RequestMapping requestMapping;
            for(Method method : methods){
                if((requestMapping = method.getDeclaredAnnotation(RequestMapping.class)) != null){
                    System.out.println(klass.getDeclaredAnnotation(Controller.class).value());
                    if (str.equals (klass.getDeclaredAnnotation(Controller.class).value() + requestMapping.value())){
                        try {
                            Object object = method.invoke(o);
                            return object;
                        }catch (ReflectiveOperationException e){
                            System.out.println(e);
                        }
                    }
                }
            }
        }
        return null;
    }
    public void insertController(String str,Object o){
        controllerBean.put(str,o);
    }
}
